package com.wingice.system.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wingice.common.page.EntityPageBean;
import com.wingice.system.entity.SysOauthClientDetails;
import com.wingice.system.mapper.SysOauthClientDetailsMapper;
import com.wingice.system.service.SysOauthClientDetailsService;
import com.wingice.utils.transfer.TransferUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.security.KeyPair;

/**
 * <p>
 * 客户端信息表 服务实现类
 * </p>
 *
 * @author 胡昊
 * @since 2021-01-13
 */
@Service
public class SysOauthClientDetailsServiceImpl extends ServiceImpl<SysOauthClientDetailsMapper, SysOauthClientDetails> implements SysOauthClientDetailsService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean insert(SysOauthClientDetails sysOauthClientDetails) {
        if (!StringUtils.hasText(sysOauthClientDetails.getPrivateKey()) || !StringUtils.hasText(sysOauthClientDetails.getPublicKey())) {
            final KeyPair pair = SecureUtil.generateKeyPair("RSA");
            String privateKey = Base64.encode(pair.getPrivate().getEncoded());
            String publicKey = Base64.encode(pair.getPublic().getEncoded());
            sysOauthClientDetails.setPrivateKey(privateKey);
            sysOauthClientDetails.setPublicKey(publicKey);
        }
        return save(sysOauthClientDetails);
    }

    @Transactional(readOnly = true)
    @Override
    public String getSysOauthClientDetailsByClientIdAndSecret(SysOauthClientDetails sysOauthClientDetails) {
        final SysOauthClientDetails oauthClientDetails = getOne(Wrappers.<SysOauthClientDetails>lambdaQuery()
                .eq(SysOauthClientDetails::getClientId, sysOauthClientDetails.getClientId())
                .eq(SysOauthClientDetails::getClientSecret, sysOauthClientDetails.getClientSecret()));
        return oauthClientDetails == null ? "" : oauthClientDetails.getPublicKey();
    }

    @Override
    public Page<SysOauthClientDetails> pageSysOauthClientDetails(EntityPageBean<SysOauthClientDetails> entityPageBean) {
        return page(TransferUtils.pageEntityToPage(entityPageBean), Wrappers.<SysOauthClientDetails>lambdaQuery()
                .eq(StringUtils.hasText(entityPageBean.getEntity().getId()), SysOauthClientDetails::getId, entityPageBean.getEntity().getId())
                .like(StringUtils.hasText(entityPageBean.getEntity().getClientName()), SysOauthClientDetails::getClientName, entityPageBean.getEntity().getClientName())
                .like(StringUtils.hasText(entityPageBean.getEntity().getClientId()), SysOauthClientDetails::getClientId, entityPageBean.getEntity().getClientId())
        );
    }
}
